'''
BUILD ANDROID APK UNDER UBUNTU CLUSTER
author:jinrui01@baidu.com
date:2013-12-18
'''
import os
import shutil
import sys 
import re
import getopt

SVN_HEADER='https://svn.baidu.com/'
TRUNK='/trunk'
BRANCHES='/branches'
REG_BRANCHES='/lbs-mobile_[0-9]{1,}-[0-9]{1,}-[0-9]{1,}_BRANCH$'
FE_FOLDER='./com_fe'
URL_ARG='-u'
COMBINE_SIGN='&&'

def get_svn_list():
    url_str=''
    opts,args = getopt.getopt(sys.argv[1:],"b:e:f:d:p:c:h:")
    for o,a in opts:
        if o in ('-b','-e','-d','-p'):
            url_str+=' '+URL_ARG+' '+str(a)
        elif o == '-f':
            fe_list = a.split(',')
            for fe_components in fe_list:
                url_str+=' '+URL_ARG+' '+str(fe_components)
    else:
        pass
    return url_str
def get_components_modules():
    module_list=[]
    opts,args = getopt.getopt(sys.argv[1:],"b:e:d:p:f:c:h:")
    for o,a in opts:
        if o == '-f':
            fe_list = a.split(',')
            for fe_component_svn in fe_list:
                if not get_module_from_svn(fe_component_svn) is '':
                    module_list.append(get_module_from_svn(fe_component_svn))
    return module_list
    
def get_compile_type():
    compile_type="release"
    opts,args = getopt.getopt(sys.argv[1:],"b:e:d:p:f:c:h:")
    for o,a in opts:
        if o == '-c':
            if a in ["debug","release"]:
                compile_type=a
    return compile_type
    
#Remove the '/trunk' or '/branches' and 'http://svn.baidu.com' from svn_url
def remove_branch_str(url,branch_mark):
    url=url[len(SVN_HEADER):]
    mark_pos=url.find(branch_mark)
    module_url=url[:mark_pos]+url[mark_pos+len(branch_mark):]
    return module_url
                                                                                                                            
#get module link from svn url given    
def get_module_from_svn(svn_url):
    module_url=''
    if not svn_url.find(TRUNK)==-1:
        module_url=remove_branch_str(svn_url,TRUNK)
    elif not svn_url.find(BRANCHES)==-1:
        module_url_with_branch=remove_branch_str(svn_url,BRANCHES)
        module_url=re.sub(REG_BRANCHES,'',module_url_with_branch)
    else:
        module_url=''
    return module_url

def get_cp_cmd_for_fe_component(module_link_list):
    cmd=''
    if len(module_link_list)>0:
        for module in module_link_list:
            cmd+=COMBINE_SIGN
            if module == 'app/search/lbs-mobile/component/place/phone':
                cmd+='rm -rf com_fe && mkdir com_fe && cd ./com_fe && mkdir place && cd .. &&'
                cmd+='cp -rf '+ module + '/*' +' '+FE_FOLDER +'/place'
            else:
                cmd+='cp -rf '+ module +' ' + FE_FOLDER
    else:
        pass
    if len(cmd)>0:
        cmd+=COMBINE_SIGN
    return cmd
def get_cp_cmd_for_testdata():
    cmd=''
    opts,args = getopt.getopt(sys.argv[1:],"b:e:d:p:f:c:h:")
    for o,a in opts:
        if o == '-d':
            module_link = get_module_from_svn(a)
            if not module_link is '':
                cmd+='cp -rf '+ module_link + ' ./android/BaiduMapFunctionTest/'
            else:
                pass
        else:
            pass
    if len(cmd)>0:
        cmd+=COMBINE_SIGN
    return cmd    
def build_on_hudson():
    if len(sys.argv[1:])<3:
        print 'Imcomplete parameters, the params should at least include the url of  base,engine and component'
        sys.exit(1)
    else:
        output_path =  os.getcwd()+'\\output'
    if(os.path.exists(output_path)):
        print('clear output dir!!')
        shutil.rmtree( output_path )
    BUILD_SUBMITTER = 'build_submitter.py'    
    
    UpdateComwebCodeCMD=' ls '# rm -rf carpool && mkdir carpool && cp -rf app/search/lbs-place/webview/carpool/*  ./carpool/ '
    UpdateComCodeCMD=' rm -rf carpool && mkdir carpool && cp -rf app/search/lbs-place/android/carpool/*  ./carpool/'    
    CpWebFileCMD=' ls '#rm -rf ./android_citybus/web/* &&  cp -rf ./webview_citybus/release/*  ./android_citybus/web/'
    getSvnRevCMD=' && echo ============ >>./output/comRev.txt && svn info ./carpool/src >>./output/comRev.txt && echo ======get comRev end======= '

    #UpdateComSDKCodeCMD=' rm -rf comwebsdk && cp -rf app/search/lbs-mobile/component/comandroid/comwebsdk . '
    #UpdateSDKWebFileCMD=' cp -rf app/search/lbs-mobile/component/comweb/websdk ./comweb/ '
    #CpSDKWebFileCMD='rm -rf ./comwebsdk/web/* && cp -rf ./comweb/websdk/release/*  ./comwebsdk/web/'
    
    CMD_ARG = get_svn_list() + ' -c' + ' "source ~/.android_env &&rm -rf output && mkdir output' + ' && ' + UpdateComwebCodeCMD +  ' && ' + UpdateComCodeCMD  + ' && '+CpWebFileCMD + '&&echo `pwd` && sh ./carpool/buildCarpool_ubuntu.sh '+ get_compile_type() +" && echo `pwd`" + getSvnRevCMD +' && ls -al "'

    CMD_ARG_PLATFORM = ' -e ubuntu'
    CMD_ARG_USER = ' -x wangshuai09'
    CMD_ARG_MODULE = ' -m app/search/lbs-place/android/carpool/'
    if(0 == os.system(BUILD_SUBMITTER + CMD_ARG_PLATFORM + CMD_ARG_USER + CMD_ARG + CMD_ARG_MODULE)):
        print ' ==== BUILD SUCCESS !! ===='
        sys.exit(0)
    else:
        print ' ==== BUILD FAILED !! ===='
        sys.exit(1)
        
if __name__ == '__main__':
    build_on_hudson()
    